#!/bin/bash

#创建一个数据库以存放账号密码
if [ ! -f db ];then
	touch db
fi

if [ ! -d log ];then
	mkdir log
	cd log
	touch login.log
	touch loginerr.log
	cd ..
fi


register(){
         read  -p  "input username:"  name
         cat db | awk  '{print $1}' | grep -w $name &> /dev/null #判断是否存在该用户
         [ $? -eq  0 ] &&  echo  "the user exit already"  &&  exit  0
         if  [ -z $name ]; then #要求非空
                 echo  "name ca not be empty"  &&  exit  0
         fi
         read  -p  "input passwd:"  passwd1
         read  -p  "input passwd again:"  passwd2
         if  [[  "$passwd1"  !=  "$passwd2"   ]] ; then #要求两次密码相同
                 echo  "two password is not equal"  &&  exit  0
         fi
         if  [ ! -z   "$passwd1"   ]; then
                 echo  "$name $passwd1"  >> db
                 echo  "register successfully"
         fi
}
login(){
 
         read  -p  "input username:"  name
         true_pd=` cat db | awk  '$1=="'$name'"' | cut -d ' ' -f 2 `
         cat db | awk  '{print $1}' | grep -w $name &> /dev/null #判断是否存在该用户
         if  [ $? -eq  0 ]; then
                 read  -p   "input passwd:"  passwd

                 if  [[  "$true_pd"  =  "$passwd"   ]]; then
                 	  time=`date +%y-%m-%d\ %H:%M:%S`
                 	  terminal=`who | awk '{print $2}'`
                	  echo -e "$name\t$time\t$terminal" >> log/login.log
                         echo  "login successfully"
                         echo  "内核版本为`uname -r`" 

                         echo  "失败登陆记录："
                         echo "`cat log/loginerr.log | awk '$1=="'$name'"'` "
                         echo  "成功登陆记录："
                         echo "`cat log/login.log | awk  '$1=="'$name'"'`"
                         sed -i "/\b$name\b/"d  log/loginerr.log
                         #注意！！外面要双引号，单引号不可支持拓展
                         #-i表示修改文件，/b为正则化，表示字符边界，保证删除abc，不会误删abcc
                         
                 else	
                 
                 	  time=`date +%y-%m-%d\ %H:%M:%S`
                	  terminal=`who | awk '{print $2}'`
                	  echo -e "$name\t$time\t$terminal" >> log/loginerr.log
                         echo  error
                 fi
         else
                 echo  "the user dont exit"
         fi
}
main(){
case  $model  in
 1) register;;
 2) login ;;
 *) exit  1 ;;
esac
 
}
cat << EOF
----choose model----
1:register
2:login
3:exit

EOF

read  -p  "model:"  model
main